package com.naihe.anderson.sms.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.entity.Note;
import com.naihe.anderson.sms.paintbrush.PaintBrushView;
import com.naihe.anderson.sms.util.FileUtil;
import com.naihe.anderson.sms.widgets.LongClickDialog;

public class PicNoteCreateActivity extends Activity implements OnClickListener {

	/**view*/
	Button graffiti_btn;
	Button camera_btn;
	Button gallery_btn;
	
	Button brush_btn;
	Button eraser_btn;
	Button backopter_btn;
	
	EditText note_title;
	EditText note_body;
	
	LinearLayout picNoteImg;
	LinearLayout brush_layout;
	LinearLayout opter_layout;
	LayoutParams params;
	PaintBrushView brushView;
	
	/**Animation*/
	ScaleAnimation topToLeftScaleAnimation;
	ScaleAnimation topToCenterScaleAnimation;
	
	Note note;
	Date dateTime = new Date();
	
	private boolean ifPicChange = false;
	private boolean isEraser = false;
	
	public static final int MSG_WHAT_MENU_COLLECTION_SESSION = 0;
	
	Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_WHAT_MENU_COLLECTION_SESSION://加密
				if(mPopupWindow == null)
					initPopupWindows();
				
				mPopupWindow.update();
				mPopupWindow.showAtLocation(findViewById(R.id.note_body), Gravity.CENTER, 0, 0);
				break;
			default:
				break;
			}
		}
		
	};
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_picnote_layout);
		
		picNoteImg = (LinearLayout) findViewById(R.id.pic_note_img);
		opter_layout = (LinearLayout) findViewById(R.id.opter_layout);
		brush_layout = (LinearLayout) findViewById(R.id.brush_layout);
		
		params = (LayoutParams) picNoteImg.getLayoutParams();
		
		graffiti_btn = (Button) findViewById(R.id.graffiti_btn);
		graffiti_btn.setOnClickListener(this);
		camera_btn = (Button) findViewById(R.id.camera_btn);
		camera_btn.setOnClickListener(this);
		gallery_btn = (Button) findViewById(R.id.gallery_btn);
		gallery_btn.setOnClickListener(this);
		
		brush_btn = (Button) findViewById(R.id.brush_btn);
		brush_btn.setOnClickListener(this);
		eraser_btn = (Button) findViewById(R.id.eraser_btn);
		eraser_btn.setOnClickListener(this);
		backopter_btn = (Button) findViewById(R.id.backopter_btn);
		backopter_btn.setOnClickListener(this);
		
		note_title = (EditText) findViewById(R.id.note_title);
		note_body = (EditText) findViewById(R.id.note_body);
		
		note = (Note) getIntent().getSerializableExtra("note");
		if(note != null){
			note_title.setText(note.title);
			if(!TextUtils.isEmpty(note.cipher)){
	        	mHandler.sendEmptyMessageDelayed(MSG_WHAT_MENU_COLLECTION_SESSION, 10);
	        } else {
	        	createBrushView(false, note.picpath);
	        	note_body.setText(note.body);
	        }
		} else {
			note_title.setText(new SimpleDateFormat("yyyy年MM月dd日").format(dateTime));
		}
		
		initAnimation();
	}
	
	private void createBrushView(boolean canDoDraw, String path){
		brushView = new PaintBrushView(PicNoteCreateActivity.this, params.width, params.height);
		brushView.setBackgroundColor(Color.TRANSPARENT);
		if(!TextUtils.isEmpty(path))
			brushView.editPicture(path + ".png");
		
		// 将view加入到布局中
		picNoteImg.removeAllViews();
		picNoteImg.addView(brushView);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 截获按键事件
		if (KeyEvent.KEYCODE_BACK == keyCode) {
			if(mPopupWindow != null && mPopupWindow.isShowing()){
				mPopupWindow.dismiss();
			} else {
				backData();
			}
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}
	
	PopupWindow mPopupWindow = null;
	EditText editText;
	private void initPopupWindows(){
		LayoutInflater mLayoutInflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);  
        View popunwindwow = mLayoutInflater.inflate( R.layout.popup_edit_layout, null);
        editText = (EditText) popunwindwow.findViewById(R.id.baseSignature_edit);
        Button checkbtn_cancel =(Button) popunwindwow.findViewById(R.id.checkbtn_cancel);
        Button checkbtn_ok =(Button) popunwindwow.findViewById(R.id.checkbtn_ok);
        TextView title_text = (TextView) popunwindwow.findViewById(R.id.title_text);
       
        editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        editText.setHint(getResources().getString(R.string.save_key_word));
        
        title_text.setText(getResources().getString(R.string.note_mima_see));
        checkbtn_cancel.setOnClickListener(PicNoteCreateActivity.this);
        checkbtn_ok.setOnClickListener(PicNoteCreateActivity.this);
        
        mPopupWindow = new PopupWindow(popunwindwow, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 
        mPopupWindow.setOutsideTouchable(false);  
        mPopupWindow.setFocusable(true);
	}
	
	private void backData(){
		String title = note_title.getText().toString();
		String body = note_body.getText().toString();
		if(TextUtils.isEmpty(title) && TextUtils.isEmpty(body)) {PicNoteCreateActivity.this.finish();return;}
		
		if(title.equals(new SimpleDateFormat("yyyy年MM月dd日").format(dateTime)) && TextUtils.isEmpty(body)) {PicNoteCreateActivity.this.finish();return;}
		
		if(note == null){//新建
			Note creatNote = new Note();
			creatNote.title = title;
			creatNote.body = body;
			creatNote.id = dateTime.getTime();
			creatNote.createTime = dateTime.getTime();
			creatNote.cipher = "";
			
			new SavePicTask(creatNote, "create").execute();
		} else {
			if(ifPicChange){
				note.title = title;
				note.body = body;
				note.createTime = dateTime.getTime();
				
				new SavePicTask(note, "update").execute();
			} else if(!note.title.equals(title) || !note.body.equals(body)){
				note.title = title;
				note.body = body;
				note.createTime = dateTime.getTime();
				
				
				Intent intent = new Intent(PicNoteCreateActivity.this, NoteActivity.class);
				intent.putExtra("type", "update");
				intent.putExtra("note", note);
				PicNoteCreateActivity.this.setResult(RESULT_OK, intent);
			} else {
				PicNoteCreateActivity.this.finish();
			}
		}
	}
	
	private void initAnimation(){
		topToLeftScaleAnimation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 1.0f,  
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f); 
		topToLeftScaleAnimation.setDuration(500);
		topToCenterScaleAnimation = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f,  
				Animation.RELATIVE_TO_SELF, 1.0f,
				Animation.RELATIVE_TO_SELF, 0.0f); 
		topToCenterScaleAnimation.setDuration(500);
	}
	
	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.checkbtn_cancel){
			mPopupWindow.dismiss();
			PicNoteCreateActivity.this.finish();
		} else if(v.getId() == R.id.checkbtn_ok){
			String signature = editText.getText().toString().trim();
			if(note.cipher.equals(signature)){
				note_body.setText(note.body);
				createBrushView(false, note.picpath);
				mPopupWindow.dismiss();
			} else {
				editText.setText("");
				Toast.makeText(PicNoteCreateActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
			}
		} else if(v.getId() == R.id.graffiti_btn){
			ifPicChange = true;
			if(brushView == null){
				createBrushView(true, "");
			} else {
				brushView.setCanDoPic(true);
			}
			Toast.makeText(PicNoteCreateActivity.this, R.string.can_do_graffiti, Toast.LENGTH_SHORT).show();
			
			opter_layout.startAnimation(topToLeftScaleAnimation);
			opter_layout.setVisibility(View.GONE);
			
			brush_layout.startAnimation(topToCenterScaleAnimation);
			brush_layout.setVisibility(View.VISIBLE);
		} else if(v.getId() == R.id.camera_btn){
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
			//下面这句指定调用相机拍照后的照片存储的路径 
			if(tempFile == null) 
				tempFile = new File(FileUtil.getPicNotePath() + PICNOTE_TEMP_NAME + ".png");
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile)); 
			startActivityForResult(intent, SELECT_PICTURE_SYSCERAME);
		} else if(v.getId() == R.id.gallery_btn){
			Intent intent = new Intent(Intent.ACTION_PICK, null);
			if(tempFile == null)
				tempFile = new File(FileUtil.getPicNotePath() + PICNOTE_TEMP_NAME+ ".png");
			/** 
			* 下面这句话，与其它方式写是一样的效果，如果： 
			* intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
			* intent.setType(""image/*");设置数据类型 
			* 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型" 
			*/
			intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*"); 
			startActivityForResult(intent, SELECT_PICTURE_SYSPIC);
		} else if(v.getId() == R.id.brush_btn){
			selectShape();
		} else if(v.getId() == R.id.eraser_btn){
			eraser();
		} else if(v.getId() == R.id.backopter_btn){
			opter_layout.startAnimation(topToCenterScaleAnimation);
			opter_layout.setVisibility(View.VISIBLE);
			
			brush_layout.startAnimation(topToLeftScaleAnimation);
			brush_layout.setVisibility(View.GONE);
		}
	}
	
	/*
	 * 选择形状
	 */
	private void selectShape() {

		new LongClickDialog(PicNoteCreateActivity.this, 
				getResources().getStringArray(R.array.select_shape_items), 
				getResources().getString(R.string.get_tuxing__title_text), new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				//调用方法setDrawTool（）进行相应的实例化
				brushView.setDrawTool(position);

				// 如果选择了图形，则将按钮eraserButton设置显示为“橡皮”
				eraser_btn.setText(R.string.eraser_btn_text);
				isEraser = false;
			}
		}).show();
	}
	/*
	 * 橡皮 按钮轮流显示“橡皮”与“画笔”;默认显示“橡皮”
	 */
	public void eraser() {
		if (isEraser) {
			// 当前显示为“画笔”
			// 调用view类（drawTool）中的方法setDrawTool()，传递参数
			brushView.setDrawTool(6);
			// 则点击后设置按钮显示为“橡皮”
			eraser_btn.setText(R.string.eraser_btn_text);
			isEraser = false;
		} else {
			// 当前显示为“橡皮”
			// 调用view类（drawTool）中的方法setDrawTool()，传递参数
			brushView.setDrawTool(10);
			// 点击后设置按钮显示为“画笔”
			eraser_btn.setText(R.string.huabi_btn_text);
			isEraser = true;
		}
	}
	
	private static int SELECT_PICTURE_SYSPIC = 1;// 返回标志位 filed
	private static int SELECT_PICTURE_SYSCERAME = 2;// 返回标志位 filed
	private static int SELECT_PICTURE = 3;// 返回标志位 filed
	private File tempFile;
	private static final String PICNOTE_TEMP_NAME = "picnote";
	public static final String PICNOTE_PREFIX = "picnote_";
	
	/**
	 * 裁剪完图片后系统调用的方法:onActivityResult
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK){
			if (requestCode == SELECT_PICTURE_SYSPIC) {
				startPhotoZoom(data.getData());
			} else if(requestCode == SELECT_PICTURE_SYSCERAME){
				startPhotoZoom(Uri.fromFile(tempFile));
			} else if(requestCode == SELECT_PICTURE){
				if(data != null){
					setPicToView(data);
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void setPicToView(Intent picdata) {
		if(brushView == null){
			createBrushView(false, PICNOTE_TEMP_NAME);
		} else {
			brushView.destroyDrawingCache();
			brushView.editPicture(PICNOTE_TEMP_NAME + ".png");
		}
	}
	
	private void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");//设置要裁剪的图片
		intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
		intent.putExtra("aspectX", 2);// 这两项为裁剪框的比例.
		intent.putExtra("aspectY", 3);// x:y=2:3
		// 如果不设置aspectX和aspectY，则可以以任意比例缩放
		intent.putExtra("outputX", params.width);
	    intent.putExtra("outputY", params.height);
	    // 输出图片的宽
		intent.putExtra("output", Uri.fromFile(tempFile));//保存到原文件
		intent.putExtra("outputFormat", "JPEG");// 返回格式

		startActivityForResult(Intent.createChooser(intent, "裁剪"), SELECT_PICTURE);
	}
	
	class SavePicTask extends AsyncTask<String, Object, Boolean>{
		
		Note picNote;
		String type;
		
		public SavePicTask(Note picNote, String type){
			this.picNote = picNote;
			this.type = type;
		}
		
		@Override
		protected void onPreExecute() {
			Toast.makeText(PicNoteCreateActivity.this, R.string.can_do_picnote, Toast.LENGTH_SHORT).show();
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			String picName = "";
			if(TextUtils.isEmpty(picNote.picpath)){
				picName = PICNOTE_PREFIX + new Date().getTime();
			} else {
				picName = picNote.picpath;
			}
			brushView.savePicture(picName + ".png");
			//
			picNote.picpath = picName;
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if(type.equals("create")){
				Intent intent = new Intent(PicNoteCreateActivity.this, NoteActivity.class);
				intent.putExtra("type", "create");
				intent.putExtra("note", picNote);
				PicNoteCreateActivity.this.setResult(RESULT_OK, intent);
			} else if(type.equals("update")){
				Intent intent = new Intent(PicNoteCreateActivity.this, NoteActivity.class);
				intent.putExtra("type", "update");
				intent.putExtra("note", note);
				PicNoteCreateActivity.this.setResult(RESULT_OK, intent);
			}
			
			picNoteImg.removeAllViews();
			brushView.destroyDrawingCache();
			brushView = null;
			System.gc();
			PicNoteCreateActivity.this.finish();
		}
	}
}
